<template>
  <div style="min-height:500px;" ref="ruleForm">
    <a-button type="primary" style="margin:40px 0 20px 0;" @click="clickPush">新增</a-button>
    <a-table ref="table" rowKey="key" :columns="columns" :dataSource="pageData" :pagination="false" />
    <j-modal :title="title" :width="600" :visible="visible" switchFullscreen @ok="handleOk" @cancel="handleCancel"
      cancelText="关闭">
      <a-form-model layout="horizontal" ref="subForm" :model="model" :rules="validatorRules" v-bind="formItemLayout">
        <z-form-item :datas="fieldArrModal" :form="model" :rules="validatorRules" :gutter="0" />
      </a-form-model>
    </j-modal>
  </div>
</template>

<script>
var phoneValidator = (rule, value, callback) => {
  if (!value || new RegExp(/^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/).test(value)) {
    callback()
  } else {
    callback('请输入正确的联系方式')
  }
}
var identityCardValidator = (rule, value, callback) => {
  if (!value || new RegExp(/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/).test(value)) {
    // console.log(getAge(value))
    
    callback()
    return getAge(value);
  } else {
    callback('请输入正确的身份证号码')
  }
}
// var ageValidator = (rule, value, callback) => {
//   // if (!value || new RegExp(/(^[0-9]*$)/).test(value)) {
    
//   if (value==22) {
//     console.log(identityCardValidator());
//     callback()
//   } else {
//     console.log(111);
//     callback('请输入正确的年龄')
//   }
// }
/**
 * 通过身份证号计算年龄
 * @param {身份证号码} idCard
 */
var getAge = (idCard) => {
  var len = (idCard + "").length;
  if (len == 0) {
    return 0;
  } else {
    if (len != 15 && len != 18) {
      //身份证号码只能为15位或18位其它不合法
      return 0;
    }
  }
  var strBirthday = "";
  if (len == 18) {
    //处理18位的身份证号码从号码中得到生日和性别代码
    strBirthday = idCard.substr(6, 4) + "/" + idCard.substr(10, 2) + "/" + idCard.substr(12, 2);
  }
  if (len == 15) {
    strBirthday = "19" + idCard.substr(6, 2) + "/" + idCard.substr(8, 2) + "/" + idCard.substr(10, 2);
  }
  //时间字符串里，必须是“/”
  var birthDate = new Date(strBirthday);
  var nowDateTime = new Date();
  var age = nowDateTime.getFullYear() - birthDate.getFullYear();
  //再考虑月、天的因素;.getMonth()获取的是从0开始的，这里进行比较，不需要加1
  if (
    nowDateTime.getMonth() < birthDate.getMonth() ||
    (nowDateTime.getMonth() == birthDate.getMonth() &&
      nowDateTime.getDate() < birthDate.getDate())
  ) {
    age--;
  }
  return age;
}

export default {
  props: ['current', 'controlPersonType', 'value'],
  mounted () {
    
    // console.log(this.$globalRelation);
  },
  data() {
    return {
      title: '新增社会关系',
      model: {},
      modelType: 'add',
      visible: false,
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 16 }
      },
      dictOptions1: [
        { text: "夫妻", value: "1" }, { text: "父子", value: "2" }, { text: "父女", value: "3" },
        { text: "母子", value: "4" }, { text: "母女", value: "5" }, { text: "儿子", value: "6" },
        { text: "女儿", value: "7" }, { text: "兄弟", value: "8" }, { text: "兄妹", value: "9" },
        { text: "姐弟", value: "10" }, { text: "姐妹", value: "11" }, { text: "其他", value: "12" },
      ],
      dictOptions2: [
        { text: "一般亲密", value: "1" }, { text: "密切的关系", value: "2" },
        { text: "离婚", value: "3" }, { text: "疏离", value: "4" }, { text: "有冲突关系", value: "5" },
      ],
      columns: [
        {
          title: '序号',
          dataIndex: 'order',
          width: 80,
          align: 'center',
          customRender: (text, record, index) => `${index + 1}`
        },
        {
          title: '关系',
          dataIndex: 'socialRelation',
          width: 80,
          align: 'center',
          customRender: text => {
            return this.$options.filters.filterArray(text, this.dictOptions1, 'value', 'text')
          }
        },
        {
          title: '姓名',
          dataIndex: 'name',
          width: 80,
          align: 'center',
          customRender: text => {
            return <j-ellipsis value={text} length={14} />
          }
        },
        {
          title: '性别',
          dataIndex: 'sex',
          width: 80,
          align: 'center',
          customRender: text => {
            return this.$filterDictTextByCache('sex', text)
          }
        },
        {
          title: '身份证号',
          dataIndex: 'identityCard',
          width: 80,
          align: 'center',
          customRender: text => {
            return text
          }
        },
        {
          title: '年龄',
          dataIndex: 'age',
          width: 80,
          align: 'center',
          customRender: text => {
            return text
          }
        },
        {
          title: '联系电话',
          dataIndex: 'phone',
          width: 80,
          align: 'center',
          customRender: text => {
            return text
          }
        },
        {
          title: '亲密关系',
          dataIndex: 'intimacyRelation',
          width: 80,
          align: 'center',
          customRender: text => {
            return this.$options.filters.filterArray(text, this.dictOptions2, 'value', 'text')
          }
        },
        {
          title: '居住地',
          dataIndex: 'address',
          width: 110,
          align: 'left',
          customRender: text => {
            return <j-ellipsis value={text} length={12} />
          }
        },
        {
          title: '工作单位',
          dataIndex: 'workUnit',
          width: 110,
          align: 'center',
          customRender: text => {
            return <j-ellipsis value={text} length={12} />
          }
        },
        {
          title: '操作',
          width: 120,
          align: 'center',
          dataIndex: 'action',
          customRender: (text, record, index) => {
            return (
              <a-space size={6}>
                <a-button type="link" style={'padding:0'} onClick={event => this.clickPush(record)}>编辑</a-button>
                <a-button type="link" style={'padding:0'} onClick={event => this.onDelete(record.key)}> 删除 </a-button>
              </a-space>
            )
          }
        }
      ],
      fieldArrModal: [
        {
          label: '社会关系',
          prop: 'socialRelation',
          tagType: 'dict-select',
          dictOptions: [
            { text: "夫妻", value: "1" }, { text: "父子", value: "2" }, { text: "父女", value: "3" },
            { text: "母子", value: "4" }, { text: "母女", value: "5" }, { text: "儿子", value: "6" },
            { text: "女儿", value: "7" }, { text: "兄弟", value: "8" }, { text: "兄妹", value: "9" },
            { text: "姐弟", value: "10" }, { text: "姐妹", value: "11" }, { text: "其他", value: "12" },
          ]
        },
        { label: '姓名', prop: 'name', tagType: 'input' },
        { label: '性别', prop: 'sex', tagType: 'dict-select', dictCode: 'sex' },
        { label: '身份证号', prop: 'identityCard', tagType: 'input' },
        { label: '年龄', prop: 'age', tagType: 'input' },
        {
          label: '亲密关系',
          prop: 'intimacyRelation',
          tagType: 'dict-select',
          dictOptions: [
            { text: "一般亲密", value: "1" }, { text: "密切的关系", value: "2" },
            { text: "离婚", value: "3" }, { text: "疏离", value: "4" }, { text: "有冲突关系", value: "5" },
          ]
        },
        { label: '联系电话', prop: 'phone', tagType: 'input' },
        { label: '居住地', prop: 'address', tagType: 'input' },
        { label: '工作单位', prop: 'workUnit', tagType: 'input' },
      ],
      validatorRules: {
        socialRelation: [{ required: true, message: '请选择社会关系!' }],
        age: [
          { required: true, message: '请输入!' },
          { validator: this.ageValidator },
        ],
        name: [{ required: true, message: '请输入!' }],
        sex: [{ required: true, message: '请选择!' }],
        identityCard: [
          { required: true, message: '请输入!', trigger: 'change'  },
          { validator: identityCardValidator },
        ],
        phone: [
          { required: true, message: '请输入!', trigger: 'change' },
          { validator: phoneValidator },
        ],
        intimacyRelation: [{ required: true, message: '请选择亲密关系!' },],
        address: [{ required: true, message: '请输入!' },],
        workUnit: [{ required: true, message: '请输入!' },],
      },
      pageData: []
    }
  },
  computed: {
    getValue() {
      let value = this.value ? this.value : []
      return value
    }
  },
  watch: {
    getValue: {
      immediate: true,
      deep: true,
      handler(val) {
        this.pageData = val.map(v => {
          return { ...v, key: v.id }
        })
      }
    },
    pageData:{
        // immediate: true,
        deep: true,
        handler(val) {
          this.$globalRelation.setmessNum(val)
          // console.log(this);
          // this.prototype.$Relation = val
          // console.log(this.$Relation);
          // console.log(this);
        }
      }
  },
  methods: {
     ageValidator(rule, value, callback){
  // if (!value || new RegExp(/(^[0-9]*$)/).test(value)) {
  if(!this.model.identityCard){
    callback('请先输入身份证')
  }
  else if (value == getAge(this.model.identityCard)) {
    callback()
  } else {
    // console.log(111);
    callback('请输入正确的年龄')
  }
},

    clickPush(record) {
      this.visible = true
      this.modelType = record && Object.keys(record).length > 0 && record.key ? 'edit' : 'add'
      this.model = this.modelType === 'edit' ? Object.assign({}, record) : {}
      this.title = this.modelType === 'edit' ? '编辑社会关系' : '新增社会关系'
    },
    handleOk() {
      let parameter = Object.assign({}, (this.modelType === 'edit' ? {} : { key: 'add_' + Date.parse(new Date()).toString() }), this.model)
      this.$refs.subForm.validate((valid) => {
        if (valid) {
          if (this.modelType === 'edit') {
            let index = this.pageData.findIndex(item => item.key === parameter.key)
            this.pageData.splice(index, 1, parameter)
          } else {
            this.pageData.push(parameter)
          }
          this.handleCancel()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    onDelete(key) {
      let that = this
      this.$confirm({
        title: `确定删除该条记录?`,
        onOk() {
          const dataSource = [...that.pageData];
          that.pageData = dataSource.filter((item) => item.key !== key)
        },
        onCancel() {
          console.log('Cancel')
        }
      })
    },
    handleCancel() {
      this.visible = false
      this.model = {}
    }
  }
}
</script>

<style scoped lang="less">

</style>
